package com.sumainfor.pc.dev.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.dev.dao.MessageMapper;
import com.sumainfor.pc.dev.dao.UtilsMapper;
import com.sumainfor.pc.dev.feign.Zfeign.ZwxTenantFeign;
import com.sumainfor.pc.dev.service.MessageService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 通知管理
 * <p>
 *
 * @author: zhoucong
 * @create: 2019-05-07 18:38
 **/
@Service
public class MessageServiceImpl implements MessageService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(MessageServiceImpl.class);
    @Autowired
    MessageMapper messageMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    ZwxTenantFeign zwxTenantFeign;
    /**
    * <p>
    * 根据发布时间查询消息内容
    * </p>
    *
    * @author: zhoucong
    * @since:
    */
    @Override
    public List<Map<String,Object>> getMessage(Map<String,Object> params){
        return messageMapper.getMessage(params);
    }

    /**
    * <p>
    * 编辑通知管理
    * </p>
    *
    * @author: zhoucong
    * @since:
    */
    @Override
    public JsonResult updateMessage(Map<String,Object> params){
        JsonResult result = new JsonResult();

        /**
         * 加锁操作
         */
        lock.lock();
        try {
            log.info("更新操作");
            params.put("by", ContextUtils.getUserId());//操作人
            params.put("term","7");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
            params.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(params);
            System.out.println("params"+params);

            if(messageMapper.updateMessage(params)<=0){
                result.putFailed("修改失败!");
            }else{
                result.putSuccess("修改成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
    * <p>
    * 删除通知管理
    * </p>
    *
    * @author: zhoucong
    * @since:
    */
    @Override
    public JsonResult deleteMessage(Map<String,Object> params){
        JsonResult result = new JsonResult();

        /**
         * 加锁操作
         */
        lock.lock();
        try {
            log.info("删除操作");
            if(messageMapper.deleteMessage(params)<=0){
                result.putFailed("删除失败!");
            }else{
                result.putSuccess("删除成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
    * <p>
    * 发布消息
    * </p>
    *
    * @author: zhoucong
    * @since:
    */
    @Override
    public JsonResult insertMessage(Map<String,Object> params){
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            log.info("增加操作");
            params.put("term", "7");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
            params.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(params);

            String UUID;
            Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                put("uuid", "MesId");
                put("database", Constants.DATA_SOURCE_TCDP);
                put("surface", "tcdp_message");
            }});
            if(uuid!=null){
                int number=Integer.valueOf(uuid.get("uuid").toString());
                UUID= ComUtils.getLocalTrmSeqNum("Mes",number);
            }else{
                UUID=ComUtils.getLocalTrmSeqNum("Mes",0);
            }
            params.put("MesId",UUID);
            params.put("CreationTime", ConvertDateTime.getCurrentTime());

            JsonResult zwxTenIdResult = zwxTenantFeign.getAllTenId();
            System.out.println("接受的租客id"+zwxTenIdResult);
            List<Map<String,Object>> zwxTenIdList = (List<Map<String, Object>>) zwxTenIdResult.get("result");
            if (zwxTenIdList.size()>0&&zwxTenIdList!=null){
                for (Map<String,Object> zwxTenIdMap:zwxTenIdList) {
                    if(MapUtils.getString(zwxTenIdMap,"TenId")!=null&&!MapUtils.getString(zwxTenIdMap,"TenId").isEmpty()) {
                        String TenId = MapUtils.getString(zwxTenIdMap, "TenId");
                        //如果创建的是新用户不通知，那就手动给所有租客添加一个系统消息
                        if (MapUtils.getInteger(params,"IfNotice")==0){
                            params.put("TenId",TenId);
                            params.put("Sysid",MapUtils.getString(params,"MesId"));
                            zwxTenantFeign.insertSysmsg(params);
                        }


                    }

                }
            }



//            if (MapUtils.getInteger(params,"IfNotice")==0){
//                params.put("Sysid",MapUtils.getString(params,"MesId"));
//                zwxTenantFeign.insertSysmsg(params);
//            }
            Integer cout =messageMapper.insertMessage(params);
            if(cout<=0){
                result.putFailed("创建失败!");
            }else{
                result.putSuccess("创建成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }


}
